package com.whmskj.xjlhsc.mobie.Scheduling.Service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhsc.jitapi.entity.Device;
import com.whmskj.xjlhsc.jitapi.mapper.DeviceMapper;
import com.whmskj.xjlhsc.mobie.Scheduling.Dto.*;
import com.whmskj.xjlhsc.mobie.Scheduling.Service.EmployeeFilesService;
import com.whmskj.xjlhsc.mobie.Scheduling.entity.yg01EmployeeFiles;
import com.whmskj.xjlhsc.mobie.Scheduling.mapper.EmployeeFilesMapper;
import com.whmskj.xjlhsc.mobie.empProPlan.entity.ProPersonnelStandConfirm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: Sakura
 * @Date: 2025/8/26 16:43
 * @Version: v1.0.0
 * @Description: TODO
 **/
@Service
public class EmployeeFilesServiceImpl extends ServiceImpl<EmployeeFilesMapper, yg01EmployeeFiles> implements EmployeeFilesService {
    @Autowired
    private EmployeeFilesMapper employeeFilesMapper;

    @Override
    public EmployeeStatisticsDTO getEmployeeStatistics() {
        Map<String, Object> statisticsMap = employeeFilesMapper.countEmployees();

        EmployeeStatisticsDTO statisticsDTO = new EmployeeStatisticsDTO();
        statisticsDTO.setTotal(Integer.parseInt(statisticsMap.get("total") != null ? statisticsMap.get("total").toString() : "0"));
        statisticsDTO.setMaleCount(Integer.parseInt(statisticsMap.get("male") != null ? statisticsMap.get("male").toString() : "0"));
        statisticsDTO.setFemaleCount(Integer.parseInt(statisticsMap.get("female") != null ? statisticsMap.get("female").toString() : "0"));

        return statisticsDTO;
    }

    @Override
    public EmployeeFilesResultDTO selectEmployeeFilesList(EmployeeFilesDTO employeeFiles) {
        // 开始分页
        Page.startPage();

        // 创建查询实体并复制参数
        yg01EmployeeFiles queryEntity = new yg01EmployeeFiles();
        // 复制所有可能存在的查询条件
        BeanUtils.copyProperties(employeeFiles, queryEntity);

        // 查询数据
        List<yg01EmployeeFiles> list = employeeFilesMapper.selectEmployeeFilesList(queryEntity);
        PageInfo<yg01EmployeeFiles> pageInfo = new PageInfo<>(list);

        // 转换为DTO
        List<EmployeeFilesDTO> dtoList = list.stream().map(item -> {
            EmployeeFilesDTO dto = new EmployeeFilesDTO();
            BeanUtils.copyProperties(item, dto);
            return dto;
        }).collect(Collectors.toList());

        // 获取统计信息
        EmployeeStatisticsDTO statistics = getEmployeeStatistics();

        // 封装返回数据
        EmployeeFilesResultDTO resultDTO = new EmployeeFilesResultDTO();
        resultDTO.setStatistics(statistics);
        resultDTO.setEmployeeList(dtoList);
        resultDTO.setTotal(pageInfo.getTotal());

        return resultDTO;
    }

    @Override
    public Map<String, Object> getScheduleOverview(ProPersonnelStandConfirm  params) {
        Map<String, Object> result = new HashMap<>();

        // 获取排班数据
        List<ProPersonnelStandConfirm> confirmList = employeeFilesMapper.selectByCondition(params);

        // 过滤条件：根据typeOfWork过滤
        String targetTypeOfWork = null;
        if (params.getEmployee() != null && StringUtils.isNotBlank(params.getEmployee().getTypeOfWork())) {
            targetTypeOfWork = params.getEmployee().getTypeOfWork();
        }

        // 创建一个新的列表来存储过滤后的结果
        List<ProPersonnelStandConfirm> filteredList = new ArrayList<>();

        // 为每个记录设置员工信息和机台信息，并根据typeOfWork过滤
        for (ProPersonnelStandConfirm confirm : confirmList) {
            if (confirm.getStaffId() != null) {
                // 根据员工ID获取员工信息
                EmployeeFilesDTO employee = getEmployeeInfoById(confirm.getStaffId());
                confirm.setEmployee(employee);

                // 如果需要根据typeOfWork过滤，且当前员工的typeOfWork不匹配，则跳过该记录
                if (targetTypeOfWork != null &&
                        !targetTypeOfWork.equals(employee.getTypeOfWork())) {
                    continue; // 跳过当前记录，不添加到filteredList中
                }

                // 处理机台信息
                if (StringUtils.isNotBlank(confirm.getMachineryObj())) {
                    confirm.setMachineryList(JSON.parseArray(confirm.getMachineryObj(), MachineryDTO.class));
                }

                // 将符合条件的记录添加到新列表中
                filteredList.add(confirm);
            } else {
                // 如果没有staffId，根据过滤条件决定是否添加
                if (targetTypeOfWork == null) {
                    // 处理机台信息
                    if (StringUtils.isNotBlank(confirm.getMachineryObj())) {
                        confirm.setMachineryList(JSON.parseArray(confirm.getMachineryObj(), MachineryDTO.class));
                    }
                    filteredList.add(confirm);
                }
            }
        }

        // 按班次分组（在过滤后再分组）
        Map<String, List<ProPersonnelStandConfirm>> classGroup = filteredList.stream()
                .collect(Collectors.groupingBy(ProPersonnelStandConfirm::getClasses));

        result.put("classGroup", classGroup);
        result.put("total", filteredList.size());

        return result;
    }




    /**
     * 获取设备列表
     * @param params
     * @return
     */
    @Override
    public Map<String, List<Device>> getDeviceList(Device params) {
        List<Device> allDevices = employeeFilesMapper.allDevice(params);

        // 按 process 分组
        return allDevices.stream()
                .collect(Collectors.groupingBy(Device::getProcess));
    }

    // ... existing code ...
    @Override
    public List<ProPersonnelStandConfirm> queryPersonnelByDevice(DeviceQueryDTO queryDTO) {
        List<ProPersonnelStandConfirm> result = new ArrayList<>();

        // 1. 如果没有指定设备ID，先根据条件查询设备
        Integer deviceId = queryDTO.getDeviceId();
        List<Integer> deviceIds = new ArrayList<>();
        if (deviceId != null) {
            deviceIds.add(deviceId);
        } else {
            Device deviceParams = new Device();
            deviceParams.setProcess(queryDTO.getProcess());
            deviceParams.setWorkShop(queryDTO.getWorkshop());
            deviceParams.setDeviceNo(queryDTO.getDeviceNo()); // 添加设备编号查询条件
            List<Device> devices = employeeFilesMapper.allDevice(deviceParams);
            deviceIds = devices.stream().map(Device::getDeviceId).collect(Collectors.toList());
        }

        if (deviceIds.isEmpty()) {
            return result;
        }

        // 将deviceIds设为final以便在lambda表达式中使用
        final List<Integer> finalDeviceIds = deviceIds;

        // 2. 查询排班确认表
        List<ProPersonnelStandConfirm> confirmList = employeeFilesMapper.selectByCondition(new ProPersonnelStandConfirm());

        // 3. 遍历确认记录，查找匹配的设备
        for (ProPersonnelStandConfirm confirm : confirmList) {
            if (StringUtils.isNotBlank(confirm.getMachineryObj())) {
                // 解析机台JSON
                List<MachineryDTO> machineryList = JSON.parseArray(confirm.getMachineryObj(), MachineryDTO.class);

                // 检查是否包含查询的设备
                boolean hasMatchingDevice = machineryList.stream()
                        .anyMatch(m -> finalDeviceIds.contains(m.getDeviceId()));

                if (hasMatchingDevice && confirm.getStaffId() != null) {
                    // 获取员工信息
                    EmployeeFilesDTO employee = getEmployeeInfoById(confirm.getStaffId());

                    // 复制原始confirm对象的属性并设置额外信息
                    ProPersonnelStandConfirm resultItem = new ProPersonnelStandConfirm();
                    resultItem.setId(confirm.getId());
                    resultItem.setDateYmd(confirm.getDateYmd());
                    resultItem.setStaffId(confirm.getStaffId());
                    resultItem.setTeamId(confirm.getTeamId());
                    resultItem.setTeamName(confirm.getTeamName());
                    resultItem.setClasses(confirm.getClasses());
                    resultItem.setProcess(confirm.getProcess());
                    resultItem.setWorkstation(confirm.getWorkstation());
                    resultItem.setWorkshop(confirm.getWorkshop());
                    resultItem.setConfirmStatus(confirm.getConfirmStatus());
                    resultItem.setMachineryObj(confirm.getMachineryObj());
                    resultItem.setCreateUserId(confirm.getCreateUserId());
                    resultItem.setCreateTime(confirm.getCreateTime());
                    resultItem.setRemark(confirm.getRemark());
                    resultItem.setEmployee(employee);
                    resultItem.setMachineryList(machineryList); // 返回完整的machineryList，包含abTag字段

                    result.add(resultItem);
                }
            }
        }

        return result;
    }
// ... existing code ...






    /**
     * 根据员工ID获取员工信息
     * @param staffId
     * @return
     */
    public EmployeeFilesDTO getEmployeeInfoById(Integer staffId) {
        // 根据员工ID查询员工信息
        yg01EmployeeFiles queryEntity = new yg01EmployeeFiles();
        queryEntity.setId(staffId);
        List<yg01EmployeeFiles> list = employeeFilesMapper.selectEmployeeFilesList(queryEntity);

        if (list != null && !list.isEmpty()) {
            EmployeeFilesDTO dto = new EmployeeFilesDTO();
            BeanUtils.copyProperties(list.get(0), dto);
            return dto;
        }

        return null;
    }


    public EmployeeFilesDTO getEmployeeInfo(yg01EmployeeFiles employeeFiles) {
        // 查询数据
        List<yg01EmployeeFiles> list = employeeFilesMapper.selectEmployeeFilesList(employeeFiles);
        if (list != null && !list.isEmpty()) {
            EmployeeFilesDTO dto = new EmployeeFilesDTO();
            BeanUtils.copyProperties(list.get(0), dto);
            return dto;
        }
        return null;
    }


}
